import React, { PureComponent } from 'react'
import { subNumber } from '../store/actionCreators'
import store from '../store'

export class Profile extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      counter: store.getState().counter
    }
    this.unSubscribe = null
  }
  componentDidMount() {
    // 订阅
    this.unSubscribe = store.subscribe(() => {
      this.setState({
        counter: store.getState().counter
      })
    })
  }
  componentWillUnmount() {
    // 取消订阅
    this.unSubscribe()
  }
  subNumber = (num) => {
    store.dispatch(subNumber(num))
  }
  render() {
    const { counter } = this.state
    return (
      <div>
        <span>Profile组件: {counter}</span>
        <div>
          <button onClick={() => this.subNumber(1)}>-1</button>
          <button onClick={() => this.subNumber(5)}>-5</button>
          <button onClick={() => this.subNumber(10)}>-10</button>
        </div>
      </div>
    )
  }
}

export default Profile